import logging
from flask import Blueprint, jsonify
from flask import current_app
from flask import g
from flask import request

from datetime import datetime

from flask import session

from ihome_tenancy import db
from ihome_tenancy.models import Order, House
from ihome_tenancy.utils.my_decorators import is_login
from ihome_tenancy.utils.response_code import RET

order_blueprint = Blueprint('order',__name__)


@order_blueprint.route('/order/house/<int:id>')
def booking_house(id):
    #查询指定编号的房屋信息
    house=House.query.get(id)
    return jsonify(house=house.to_dict())

@order_blueprint.route('/order/',methods=['POST'])
def booking():
    '''订单'''
    #获取数据
    house_id = request.form.get('house_id')
    start_date = datetime.strptime(request.form.get('start_date'),'%Y-%m-%d')
    end_date = datetime.strptime(request.form.get('end_date'),'%Y-%m-%d')

    #教研数据
    if not all([house_id,start_date,end_date]):
        return jsonify(code=RET.PARAMERR,msg='参数不全')

    if start_date > end_date:
        return jsonify(code=RET.PARAMERR,msg='日期参数有误')

    #查询房屋信息
    try:
        house = House.query.get(house_id)
    except Exception as e:
        logging.error(e)
        return jsonify(code=RET.DATAERR,msg='c查询失败')

    #数据入库
    order = Order()
    order.user_id = session['user_id']
    order.house_id = house_id
    order.begin_date = start_date
    order.end_date = end_date
    order.days = (end_date-start_date).days+1
    order.house_price = house.price
    order.amount = order.house_price*order.days

    try:
        order.add_update()
    except:
        logging.error('下订单-出错')
        return jsonify(code=RET.DBERR,msg='更新失败')


    return jsonify(code=RET.OK,msg='可提交订单')

@order_blueprint.route('/order/<int:id>', methods=['PUT'])
def stutas(id):
    #修改订单状态
    #获取数据
    stutas=request.form.get('status')
    order=Order.query.get(id)
    order.status=stutas
    #校验数据
    if stutas=='REJECTED':
        order.comment=request.form.get('comment')
    if stutas =='COMPLETE':
        order.comment = request.form.get('comment')
    #数据入入库
    order.add_update()
    #返回相应
    return jsonify(code=RET.OK,msg="OK")

@order_blueprint.route('/order/fd')
@is_login
def order_fd():
    user_id=g.user.id
    #根据用户查找自己的房子
    house_list = House.query.filter(House.user_id == user_id)
    #获取到房子的id
    house_list_id = [house.id for house in house_list]
    #获取订单中所有的房子
    order = Order.query.filter(Order.house_id.in_(house_list_id)).order_by(Order.id.desc())
    #遍历订单中的所有房子
    olist = [k.to_dict() for k in order]
    #返回数据
    return jsonify(code=RET.OK , olist=olist)

@order_blueprint.route('/order/')
@is_login
def my_order():
    #显示订单的信息
    user_id=g.user.id
    #查询所有订单的信息
    order_object=Order.query.filter(Order.user_id==user_id).order_by(Order.id.desc())

    olist=[i.to_dict() for i in order_object]

    return jsonify(code=RET.OK,msg='ok',olist=olist)
